﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Barbar.UrlGuard.BL.Concrete {
  internal class SymmetricPasswordService : ISymmetricPasswordService {
    const byte START_HASH_CHAR = 97;

    public string EncryptPassword(string plainTextPassword) {
      if (string.IsNullOrEmpty(plainTextPassword))
        return string.Empty;

      byte[] buffer = Encoding.UTF8.GetBytes(plainTextPassword);
      byte hashChar = START_HASH_CHAR;
      for (int i = 0; i < buffer.Length; i++) {
        buffer[i] ^= hashChar;
        hashChar = buffer[i];
      }
      return Convert.ToBase64String(buffer);
    }

    public string DecryptPassword(string encryptedPassword) {
      if (string.IsNullOrEmpty(encryptedPassword))
        return string.Empty;

      byte[] buffer = Convert.FromBase64String(encryptedPassword);
      byte hashChar = START_HASH_CHAR;
      for (int i = 0; i < buffer.Length; i++) {
        buffer[i] ^= hashChar;
        hashChar = (byte)(buffer[i] ^ hashChar);
      }

      return Encoding.UTF8.GetString(buffer);
    }
  }
}
